package com.cch.cooperation.api.support.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.cch.cooperation.api.common.util.ImgUtil;
import com.cch.cooperation.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;


/**
 * 内容审核
 *
 * @author cch
 */
@Slf4j
@Service
public class ContentCheckServiceImpl {

    @Resource
    private AipContentCensor aipContentCensor;

    private final static Integer CONCLUSION_TYPE_REJECT = 2;

    public void checkText(String text) {
        if (StrUtil.isEmpty(text)) {
            return;
        }
        JSONObject res = aipContentCensor.textCensorUserDefined(text);
        log.info("[内容审核-文本] 结果:{}", res);
        if (res.has("conclusionType") && CONCLUSION_TYPE_REJECT.equals(res.get("conclusionType"))) {
            throw new BizException("内容违规，请修改后再发布");
        }
    }

    public void checkImage(InputStream inputStream) {
        if (Objects.isNull(inputStream)) {
            return;
        }
        try {
            byte[] buff = ImgUtil.compress(inputStream, 800, 800);
            if (ArrayUtil.isEmpty(buff)) {
                return;
            }
            JSONObject res = aipContentCensor.imageCensorUserDefined(buff, null);
            log.info("[内容审核-图片] 结果:{}", res);
            if (res.has("conclusionType") && CONCLUSION_TYPE_REJECT.equals(res.get("conclusionType"))) {
                throw new BizException("图片违规，请修改后再上传");
            }
        } catch (IOException e) {
            log.error("[内容审核-图片] 异常", e);
        }
    }

}
